package edu.dlust.trading_platform;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBase.Redis;
import edu.dlust.trading_platform.ability.SendMail;
import edu.dlust.trading_platform.DataBean.random;
import edu.dlust.trading_platform.DataBean.userdata;

public class QQLoginActivity extends AppCompatActivity {
    private ImageView back;
    private EditText mail,code;
    private Button login,get;
    private boolean waits = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qqlogin);
        get();
        login();
        back();
    }

    private void get(){
        mail = findViewById(R.id.editText_mail);
        login = findViewById(R.id.button_login);
        get = findViewById(R.id.button_get_code_mail);
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = mail.getText().toString();
                String sql = "SELECT Uid,UName From LOGINID WHERE Mail = ?";
                if(waits){
                    if (mail.length() == 0) {
                        Toast.makeText(QQLoginActivity.this, "请正确填写邮箱", Toast.LENGTH_SHORT).show();
                    } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Connection con = MySQL.getConnection();
                            PreparedStatement ps = con.prepareStatement(sql);
                            ps.setString(1,email);
                            ResultSet rs = ps.executeQuery();
                            int row = 0;
                            while (rs.next()){
                                row++;
                            }
                            if (row >1){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(QQLoginActivity.this, "该邮箱绑定多个账号，无法使用邮箱登录！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }else if (row == 1){
                                random random = new random();
                                Redis redis = new Redis();
                                int code = random.create();
                                SendMail sendMailTask = new SendMail(email, code);
                                redis.create(email,code);
                                sendMailTask.execute();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(QQLoginActivity.this, "已成功发送验证码", Toast.LENGTH_SHORT).show();
                                        waits = false;
                                        waiting();
                                    }
                                });
                            }else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(QQLoginActivity.this, "账号不存在！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                            con.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                    }
                }else {
                    Toast.makeText(QQLoginActivity.this, "请等待60秒后再申请,重复申请仅生效最新验证码！", Toast.LENGTH_SHORT).show();
                }
            }

        });

    }
    private void login(){
        mail = findViewById(R.id.editText_mail);
        code = findViewById(R.id.editText_code_mail);
        login = findViewById(R.id.button_login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = mail.getText().toString();
                String codes = code.getText().toString();
                if (email.equals("") || codes.equals("")){
                    Toast.makeText(QQLoginActivity.this, "请正确填写以上信息", Toast.LENGTH_SHORT).show();
                }else {
                    if(!CheckCode(email,Integer.parseInt(codes))) {
                        Toast.makeText(QQLoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    }else {
                        String sql = "SELECT Uid,UName From LOGINID WHERE Mail = ?";
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                        try {
                            Connection con = MySQL.getConnection();
                            PreparedStatement ps = con.prepareStatement(sql);
                            ps.setString(1,email);
                            ResultSet rs = ps.executeQuery();
                            String uid = null,name = null;
                            if (rs.next()){
                                uid = rs.getString("Uid");
                                name = rs.getString("UName");
                            }
                            userdata.setUid(uid);
                            userdata.setName(name);
                            con.close();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent = new Intent(QQLoginActivity.this,HomePageActivity.class);
                                    startActivity(intent);
                                    QQLoginActivity.this.finish();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                            }
                        }).start();
                    }
                }
            }
        });
    }

    public void waiting() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                waits = true;
                timer.cancel(); // 取消定时任务
            }
        }, 60000); // 60秒等待时间，1秒 = 1000毫秒
    }

    public boolean CheckCode(String mail, int check) {
        FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                Redis redis = new Redis();
                int result = Integer.parseInt(redis.find(mail));
                return result == check;
            }
        });

        new Thread(futureTask).start();

        try {
            return futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }
    }

    private void back() {
        back = findViewById(R.id.mail_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(QQLoginActivity.this,LoginActivity.class);
                startActivity(intent);
                QQLoginActivity.this.finish();
            }
        });
    }
}